package cn.pugle.base.net.socket.tmp;

import cn.pugle.base.net.socket.client.CONS;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * stream mass <br/>
 * stream 里面是有buffer的? jvm提供了么?? 系统提供了? <br/>
 * client写了一大坨, 这里不读, 到底缓存在哪, 超过了怎么办, 客户端<del>会不</del>会卡住? <br/>
 *
 * http://blog.csdn.net/lishanmin11/article/details/77092652 <br/>
 *
 *
 * @author tzp
 * @date 15-12-7
 */
public class LateStreamServer {
    static ExecutorService threadPool;

    static {
        threadPool = Executors.newFixedThreadPool(10);
    }

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(CONS.SERVER_PORT, 100, CONS.inetAddress);
            Socket incomeSocket;
            System.out.println("begin to accept connection");
            while (!Thread.interrupted()) {
                incomeSocket = serverSocket.accept();
                threadPool.execute(new MySocketWorker(incomeSocket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class MySocketWorker implements Runnable {
        Socket socketToTreat;

        public MySocketWorker(Socket socketToTreat) {
            this.socketToTreat = socketToTreat;
        }

        @Override
        public void run() {
            try {
                System.out.println("connection comming in");
                InputStream in = socketToTreat.getInputStream();
                Thread.sleep(1000 * 60);
                String strIn = null;
                int rd;
                long numBytes = 0L;
                while ((rd = in.read()) != -1) {
                    numBytes++;
//                    System.out.println("It says: " + rd);
                }
                System.out.println("bytes num: " + numBytes);
                System.out.println("connection finish");
                socketToTreat.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
